<template>
  <div class="main">
    <!-- 数据查询区：表单 -->
    <el-form ref="queryRef" :model="queryParams" :inline="true">
      <el-form-item label="房型" prop="roomTypeId">
        <el-select
          v-model="queryParams.roomTypeId"
          style="width: 200px"
          placeholder="请选择房型"
          @change="handleQuery"
        >
          <el-option
            v-for="item in roomTypesOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-input-number
          v-model.number="queryParams.floor"
          clearable
          style="width: 100px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="startDate" label="开始日期">
        <el-date-picker
          v-model="queryParams.startDate"
          disabled
          style="width: 140px"
          type="date"
          placeholder="Pick a day"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item prop="endDate" label="离店日期">
        <el-date-picker
          v-model="queryParams.endDate"
          type="date"
          style="width: 140px"
          placeholder="Pick a day"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <!-- <el-form-item>
        <div class="block">
          <el-date-picker
            v-model="valueList"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
          />
        </div>
        <div>
          开始日期: {{ valueList ? valueList[0] : "" }}
          <br />
          结束日期: {{ valueList ? valueList[1] : "" }}
        </div>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery(queryRef, 'query')"
          >重置</el-button
        >
        <el-button
          type="primary"
          icon="Search"
          style="margin-left: 30px"
          @click="bookingDialogOpen = true"
          >预定入住</el-button
        >
      </el-form-item>
    </el-form>

    <el-divider />
    <!-- 数据展示区：卡片 -->
    <el-row v-loading="loading" :gutter="7" style="margin-left: 5px">
      <el-col
        v-for="room in RoomsDataList"
        :key="room.id"
        :span="4"
        style="margin-bottom: 5px"
      >
        <el-card :style="cardStyle(room)" @click="checkInFrom(room)">
          <template #header>
            <div class="card-header">
              <span style="font-size: 30px">{{ room.roomNumber }}</span>
              <br />
              <span>{{ room.name }}</span>
            </div>
          </template>
          <div>
            <p>状态: {{ room.status }}</p>
            <br />
            <p>
              价格: <span style="font-size: 20px">{{ room.finalPrice }}¥</span>
            </p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据编辑区：入住表单 -->
    <el-dialog v-model="dialogOpen" :title="title" width="520">
      <!-- 前面是子组件,后面是本地 -->
      <RoomSaleForm
        :dialogOpen="dialogOpen"
        :bookingDialogOpen="bookingDialogOpen"
        :roomNumber="roomNumber"
        :bookingData="bookingData"
        @close="handleCloseDialog"
      />
    </el-dialog>
    <el-dialog v-model="bookingDialogOpen" :title="title" width="1000">
      <el-form ref="bookQueryRef" :model="bookQueryParams" :inline="true">
        <el-form-item label="联系人" prop="contact">
          <el-input
            v-model.number="bookQueryParams.contact"
            placeholder="请输入联系人名字"
            clearable
            style="width: 140px"
            @keyup.enter="getBookingInfoList()"
          />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model.number="bookQueryParams.phone"
            placeholder="请输入电话"
            clearable
            style="width: 140px"
            @keyup.enter="getBookingInfoList()"
          />
        </el-form-item>
        <el-form-item prop="startDate">
          <el-date-picker
            v-model="bookQuery.startDate"
            style="width: 140px"
            type="date"
            placeholder="Pick a day"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate2"
          />
        </el-form-item>
        <el-form-item prop="startDate">
          <el-button type="primary" icon="Search" @click="getBookingInfoList()"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery(bookQueryRef, 'book')"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-row>
        <el-table
          v-loading="bookLoading"
          :data="dataList"
          style="font-size: 17px"
        >
          <el-table-column
            prop="name"
            label="房型名称"
            align="center"
            width="200"
          />
          <el-table-column
            prop="roomNumber"
            label="房间号"
            align="center"
            width="100"
          />
          <el-table-column
            prop="contact"
            label="联系人"
            align="center"
            width="80"
          />
          <el-table-column
            prop="phone"
            label="电话号码"
            align="center"
            width="150"
          />
          <el-table-column
            prop="startDate"
            label="开始日期"
            align="center"
            width="150"
          />
          <el-table-column
            prop="leaveDate"
            label="结束日期"
            align="center"
            width="150"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                size="large"
                @click="bookCheckIn(scope.row)"
                >入住</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-dialog>
    <!-- 数据展示区：分页加载 -->
    <el-pagination
      v-model:page-size="queryParams.pageSize"
      v-model:current-page="queryParams.pageNum"
      style="margin-top: 20px"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 数据编辑区：新增/修改对话框 默认不显示 -->
    <div v-show="false" id="message" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRef, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { dayjs, ElMessage, ElMessageBox } from "element-plus";
import { listAllRoomTypes } from "@/api/roomtypes";
import { getRoomPricePageWithPrice } from "@/api/roomsale";
import type { RoomPriceDTO } from "@/api/roomsale";
import type { RoomTypesDTO } from "@/api/rooms";
import type { CustomerInfo, QueryParams } from "@/api/roomsale";
import RoomSaleForm from "@/views/hotel/roomcheck/form.vue";
import { BookingQuery, getBookingInfo } from "@/api/roompre";
import { start } from "nprogress";
onMounted(() => {
  // 挂载后加载数据
  getList();
  getBookingInfoList();
  getRoomTypesOptions();
});
const disabledDate = time => {
  // 如果 valueList 中有开始日期，则禁用这个日期之前的所有日期
  // 允许用户选择等于开始日期的那一天
  // 允许选择开始日期当天，所以使用 '<=' 来禁用小于等于开始日期的时间
  return time.getTime() < new Date(dayjs().format("YYYY-MM-DD")).getTime();
};
const disabledDate2 = time => {
  return (
    time.getTime() <=
    new Date(dayjs().format("YYYY-MM-DD")).getTime() - 24 * 60 * 60 * 1000
  );
};
const queryRef = ref<FormInstance>();
const bookQueryRef = ref<FormInstance>();
const roomTypesOptions = ref<RoomTypesDTO[]>([]);
function getRoomTypesOptions() {
  listAllRoomTypes().then(response => {
    roomTypesOptions.value = response.data;
  });
}

const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
const query = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 24,
  floor: undefined,
  status: "空闲",
  roomTypeId: undefined,
  date: undefined,
  startDate: today.toISOString().split("T")[0], // 格式化为 YYYY-MM-DD
  endDate: tomorrow.toISOString().split("T")[0]
});
const queryParams = toRef(query);
// 数据查询区--> 查询按钮
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

const loading = ref<boolean>(false); // table数据加载遮罩
const total = ref<number>(0); // table数据总数
const RoomsData = reactive<RoomPriceDTO[]>([]); // table数据
const RoomsDataList = toRef(RoomsData);
function getList() {
  loading.value = true;
  /** 调用后端分页查询接口 */
  getRoomPricePageWithPrice(queryParams.value).then(response => {
    RoomsDataList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}

const resetQuery = (formEl: FormInstance | undefined, type) => {
  if (!formEl) return;
  formEl.resetFields();
  // getList();
  if (type === "query") {
    getList();
  } else if (type === "book") {
    getBookingInfoList();
  }
};

const bookLoading = ref<boolean>(false); // table数据加载遮罩
const tableData = reactive([]);
const dataList = ref(tableData);
const bookQuery = reactive<BookingQuery>({
  contact: undefined,
  phone: undefined,
  startDate: today.toISOString().split("T")[0]
});
const bookQueryParams = toRef(bookQuery);
// 数据查询区--> 查询按钮
function handleBookQuery() {
  queryParams.value.pageNum = 1;
  getBookingInfoList();
}
function getBookingInfoList() {
  bookLoading.value = true;
  /** 调用后端分页查询接口 */
  getBookingInfo(bookQueryParams.value).then(response => {
    dataList.value = response.data;
    bookLoading.value = false;
  });
}
const bookingData = ref({
  contact: undefined,
  phone: undefined,
  startDate: undefined,
  endDate: undefined
});

function bookCheckIn(row) {
  dialogOpen.value = true;
  roomNumber.value = row.roomNumber;
  bookingData.value = row;
}

function cardStyle(room) {
  let backgroundColor;

  switch (room.status) {
    case "空闲":
      backgroundColor = "#00993340";
      break;
    case "已预定":
      backgroundColor = "#FFFF0040";
      break;
    case "已入住":
      backgroundColor = "#FF333390";
      break;
    case "打扫中":
      backgroundColor = "#00CCFF50";
      break;
  }
  return {
    backgroundColor: backgroundColor
  };
}
const dialogOpen = ref<boolean>(false); //对话框打开
const bookingDialogOpen = ref<boolean>(false); //对话框打开
const title = ref<string>("");

const roomNumber = ref("");

function checkInFrom(room) {
  roomNumber.value = room.roomNumber;
  console.log("点击卡片时", roomNumber.value);
  dialogOpen.value = true;
}

/** 关闭对话框 */
function handleCloseDialog() {
  dialogOpen.value = false;
  console.log(
    "关闭对话框handleCloseDialog",
    roomNumber.value,
    bookingDialogOpen.value
  );
  roomNumber.value = "";
  getList();
}
// 分页--> 修改每页数据数（5｜10｜20｜30）
function handleSizeChange(val: number) {
  queryParams.value.pageSize = val;
  getList();
}
//分页--> 修改当前页
function handleCurrentChange(val: number) {
  queryParams.value.pageNum = val;
  getList();
}
</script>

<style lang="scss" scoped>
.el-card:hover {
  cursor: pointer;
  transition: transform 0.3s;
  transform: scale(1.05);
}

.room-popover {
  padding: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.detail-item label {
  min-width: 70px;
  margin-right: 10px;
  color: #666;
}

.detail-item span {
  font-size: 1500;
  font-weight: 500;
  color: #333;
}
</style>
